package cn.itsource.hrm.config;

import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

//rabbitMQ的配置
@Configuration
public class RabbitMQConfig {

    public static final String DEAD_QUEUE_ORDER = "dead_Queue_order"; //死信队列
    public static final String DELAY_QUEUE_ORDER = "delay_Queue_order"; //延迟队列
    public static final String ORDER_EXCHANGE = "orderExchange"; //交换机
    public static final String ROUTINGKEY_QUEUE_DELAY="delay.message"; //延迟队列routingkey
    public static final String ROUTINGKEY_QUEUE_DEAD="order.message"; //预创订单routingkey

    //定义2个队列：1 死信队列 2 延迟队列
    @Bean(DEAD_QUEUE_ORDER)
    public Queue deadQueue(){
        Map<String,Object> map = new HashMap<>();
        map.put("x-dead-letter-exchange", ORDER_EXCHANGE);    //过期的消息给哪个交换机的名字
        map.put("x-dead-letter-routing-key", ROUTINGKEY_QUEUE_DELAY);   //死信交换机把消息个哪个个routingkey
        map.put("x-message-ttl", 30000);
        return new Queue(DEAD_QUEUE_ORDER,true,false,false,map);
    }
    @Bean(DELAY_QUEUE_ORDER)
    public Queue delayQueue(){
        return new Queue(DELAY_QUEUE_ORDER,true);
    }

    //订单交换机：普通交换机和死信交换机合二为1
    @Bean(ORDER_EXCHANGE)
    public Exchange orderExchange(){
        return ExchangeBuilder.topicExchange(ORDER_EXCHANGE).durable(true).build();
    }


    //绑定死信队列到交换机
    @Bean
    public Binding deadQueueBinding(@Qualifier(ORDER_EXCHANGE) Exchange exchange,
                                    @Qualifier(DEAD_QUEUE_ORDER) Queue deadQueue){
        return BindingBuilder.bind(deadQueue).to(exchange).with(ROUTINGKEY_QUEUE_DEAD).noargs();
    }

    //绑定延迟队列到交换机
    @Bean
    public Binding delayQueueBinding(@Qualifier(ORDER_EXCHANGE) Exchange exchange,
                                    @Qualifier(DELAY_QUEUE_ORDER) Queue delayQueue){
        return BindingBuilder.bind(delayQueue).to(exchange).with(ROUTINGKEY_QUEUE_DELAY).noargs();

    }


}